package com.gigalaxy.utils
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;

	public class GGURLLoader
	{
		private var _request:URLRequest;
		private var _loader:URLLoader;
		private var _result:Function;
		private var _error:Function;

		/**
		 * function result(data:Object):void<br />
		 * function error(message:String):void
		 */
		public function GGURLLoader(url:String = "", result:Function = null, error:Function = null)
		{
			_result = null;
			_error = null;

			if (url != "")
			{
				load(url, result, error);
			}
		}

		/**
		 * function result(data:Object):void<br />
		 * function error(message:String):void
		 */
		public function load(url:String, result:Function = null, error:Function = null):void
		{
			if (url != "")
			{
				_result = result;
				_error = error;

				_loader = new URLLoader();
				_request = new URLRequest(url);

				_loader.addEventListener(Event.COMPLETE, _completeHandler, false, 0, true);
				_loader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler, false, 0, true);
				_loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler, false, 0, true);

				_loader.load(_request);
			}
		}

		protected function securityErrorHandler(event:SecurityErrorEvent):void
		{
			if (_error != null)
			{
				_error.call(null, SecurityErrorEvent.SECURITY_ERROR);
			}
		}

		protected function ioErrorHandler(event:IOErrorEvent):void
		{
			if (_error != null)
			{
				_error.call(null, IOErrorEvent.IO_ERROR);
			}
		}

		protected function _completeHandler(event:Event):void
		{
			if (_result != null)
			{
				_result.call(null, _loader.data as Object);
			}
		}
	}
}
